<template>
    <div class="commodity" :style="{ 'height': productsHeight }">
        <div class="header">
            <van-nav-bar :title="type" left-arrow @click-left="routerOutClick" />
        </div>
        <searchHome v-model:value="queryParams.content" @onSubmit="onRefresh" :isFiltrate="false" />
        <div class="commodity_classify">
            <div class="commodity_classify_item" @click="categoryIsShow = true">
                <span>{{ queryParams.categoryIdList.length ? '多品类' : '商品类目' }}</span>
                <img src="@/assets/commodity/icon_heisexiasanjiao.png" alt="">
            </div>
            <category :isShow="categoryIsShow" v-model:value="queryParams.categoryIdList" :multiple="true"
                @leftClick="categoryIsShow = false" @onSubmit="categorySubmit" />
            <div class="home-index-data-date">
                <div class="home-index-data-date-first">
                    <div class="home-index-data-date-first-date" @click="showPicker = true">
                        {{ currentDateFormat }}
                    </div>
                    <van-image width="10" height="6" :src="lsxsjImage" />
                </div>
                <van-popup v-model:show="showPicker" position="bottom">
                    <van-date-picker @confirm="onConfirm" @cancel="showPicker = false" v-model="currentDate"
                        :max-date="maxDate" />
                </van-popup>
                <div class="home-index-data-date-middle">至</div>
                <div class="home-index-data-date-second">
                    <div class="home-index-data-date-second-date" @click="showPickerBottom = true">
                        {{ currentDateFormatInterval }}
                    </div>
                    <van-image width="10" height="6" :src="lsxsjImage" />
                </div>
                <van-popup v-model:show="showPickerBottom" position="bottom">
                    <van-date-picker @confirm="onConfirmBottom" @cancel="showPickerBottom = false"
                        v-model="currentDateBottom" :min-date="minDate" />
                </van-popup>
            </div>
        </div>
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :style="{ 'height': refreshHeight }">
            <van-list v-model:loading="loading" :finished="finished" @load="onLoad">
                <template v-slot:finished>
                    <div class="nothing_div" v-if="list.length == 0 && !refreshing">
                        <van-image :src="nothingData"></van-image>
                        <div class="nothing_font">暂无数据</div>
                    </div>
                </template>
                <van-swipe-cell v-for="item in list" :key="item.id">
                    <commodityList :data="item" :type="type" @click="routerGo(item.type, item.productId)" />
                </van-swipe-cell>
            </van-list>
        </van-pull-refresh>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, computed, onActivated } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { getEnvValue } from "@/utils/index";
import { selectRecruiterSelection, selectStockOut } from '@/api/operation/index'
const lsxsjImage = new URL("@/assets/home/icon_lansexiasanjiao.png", import.meta.url).href;
// 类目
import category from '@/components/category/index.vue'
// 头部搜索框
import searchHome from '@/views/productHome/productLists/components/searchHome/index.vue'
// 列表
import commodityList from './components/commodityList.vue'
const route = useRoute();
/** 开始时间 */
const startTime: any = computed(() => {
    return route.query.startTime;
});
/** 结束时间 */
const endTime: any = computed(() => {
    return route.query.endTime;
});
/** 筛选类型 */
const type: any = computed(() => {
    return route.query.type;
});

const nothingData = new URL("@/assets/porduct/icon_zanwushuju.png", import.meta.url).href


// 日期筛选
const showPicker = ref(false);
const showPickerBottom = ref(false)
const currentDateFormat = ref<any>(startTime.value)
const currentDateFormatInterval = ref<any>(endTime.value)
const currentDate = ref([startTime.value.split('-')[0], startTime.value.split('-')[1], startTime.value.split('-')[2]])
const currentDateBottom = ref([endTime.value.split('-')[0], endTime.value.split('-')[1], endTime.value.split('-')[2]])
/** 日期选择 */
const onConfirm = () => {
    showPicker.value = false;
    currentDateFormat.value = currentDate.value.join("-")
    onRefresh()
};
/** 日期选择 */
const onConfirmBottom = () => {
    showPickerBottom.value = false
    currentDateFormatInterval.value = currentDateBottom.value.join("-")
    onRefresh()
}

// 限制最大可选时间
const maxDate = computed(() => {
    return new Date(currentDateBottom.value.join('/'))
})

// 限制最小可选时间
const minDate = computed(() => {
    return new Date(currentDate.value.join('/'))
})


const router = useRouter();
// 类目开关
const categoryIsShow = ref(false)

const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const list = ref<any>([]);
// 限制连续刷新数据重复问题
const refreFlag = ref(true)

// 查询列表参数
const queryParams = ref({
    content: '',
    categoryIdList: [],
    categoryName: '',
    pageSize: 10,
    pageNum: 1,
})

const productsHeight = ref()
const refreshHeight = ref()
const defaultPhoneHeight = ref(0) //屏幕默认高度
const nowPhoneHeight = ref(0) //屏幕现在的高度
const emits = defineEmits(['doShow'])
const vantListScrollTop = ref<any>(0) // 滚动位置

// 在组件挂载完成后添加事件监听器
onMounted(() => {
    defaultPhoneHeight.value = window.innerHeight;
    // 添加事件监听器
    window.addEventListener('resize', handleResize);
    functionScroll('init')
})
// 处理窗口大小变化的函数
const handleResize = () => {
    nowPhoneHeight.value = window.innerHeight;
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    functionScroll('delete')
});
/** 缓存页面进度条 */
const functionScroll = (type: string) => {
    const dom: any = document.querySelector('.van-pull-refresh')
    if (type === 'init') {
        dom?.addEventListener('scroll', (e: any) => {
            vantListScrollTop.value = e.target.scrollTop
        })
    } else if (type === 'delete') {
        dom?.removeEventListener('scroll', () => { });
    } else if (type === 'black') {
        dom.scrollTop = vantListScrollTop.value
    }
}
onActivated(() => {
    functionScroll('black')
})
watch(nowPhoneHeight, () => {
    if (defaultPhoneHeight.value != nowPhoneHeight.value) {
        // 当软键盘弹出,改变bottomIsSHow变量然后去控制bottom的显示与隐藏
        productsHeight.value = '100vh'
        refreshHeight.value = 'calc(100vh - 42.6666vw)'
        emits('doShow', false)
    } else {
        // 相等代表软键盘收起后,与上同理
        productsHeight.value = 'calc(100vh - 13.333333vw)'
        refreshHeight.value = 'calc(100vh - 56vw)'
        emits('doShow', true)
    }
})
// 获取列表数据
const getList = async () => {
    let res: any;
    if (type.value === '招商选品') {
        res = await selectRecruiterSelection({
            ...queryParams.value,
            selectionStartTime: currentDateFormat.value,
            selectionEndTime: currentDateFormatInterval.value,
        })
    } else {
        res = await selectStockOut({
            ...queryParams.value,
            selectionStartTime: currentDateFormat.value,
            selectionEndTime: currentDateFormatInterval.value,
        })
    }
    const { rows = [], total = 0 } = res
    refreFlag.value = true
    // 空数据 停止加载
    if (rows.length == 0) {
        list.value = [];
        finished.value = true;
        return;
    }
    // 有数据 赋值列表 加载状态结束
    rows.forEach((item) => {
        finished.value = false;
        if (item.productImage) {
            item.productImages = getEnvValue("VITE_APP_PIC_URL") + item.productImage.split(',')[0];
        } else {
            item.productImages = "";
        }
        list.value.push(item);
    });
    loading.value = false;
    refreshing.value = false;
    // 如果list长度大于等于总数据条数，数据全部加载完成
    if (list.value.length >= total) {
        finished.value = true; //结束加载
    }
}

// 导航返回
const routerOutClick = () => {
    router.push({
        path: '/operation/operatepage',
        query: {
            startTime: startTime.value,
            endTime: endTime.value
        }
    })
}
// 跳转商品详情
const routerGo = (type: any, id: string) => {
    if (type == 1) {
        router.push({
            path: `/researchBasicsDetail/${id}`
        })
    } else {
        router.push({
            path: `/operationBasicsDetail/${id}`
        })
    }
}

/** 加载更多 */
const onLoad = async () => {
    getList();
    queryParams.value.pageNum++;
};
/** 下拉 */
const onRefresh = () => {
    if (refreFlag.value) {
        refreFlag.value = false
        finished.value = false; // 清空列表数据
        refreshing.value = false;
        loading.value = true; // 加载状态
        queryParams.value.pageNum = 1; // 分页数赋值为1
        list.value = []; // 清空数组
        onLoad(); // 重新加载数据
    } else {
        finished.value = false;
        refreshing.value = false;
    }
};
// 商品类目选择完成
const categorySubmit = () => {
    categoryIsShow.value = false
    onRefresh()
}
</script>

<style lang="less" scoped>
@import url(@/views/operation/operationHomeList/components/style/index.less);

:deep(.van-pull-refresh) {
    height: calc(100vh - 185px) !important;
    overflow: scroll;
    background: #fff;
}

.commodity {
    height: 100vh !important;
}

.commodity_classify_item {
    width: 115px !important;
    flex: none !important;
    justify-content: flex-start !important;
}

.commodity_classify {
    margin-bottom: 0 !important;
    padding: 0 10px !important;
}

.header {
    background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
    filter: blur(0px);
    height: 90px;
    padding-top: 44px;
    box-sizing: border-box;

    :deep(.van-icon-arrow-left) {
        color: #1a1b1c !important;
    }

    :deep(.van-nav-bar) {
        background: none !important;
    }

    :deep(.van-nav-bar__content) {
        background-color: transparent !important;
    }
}

.home-index-data-date {
    padding-right: 15px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #0094ff;
    width: calc(100% - 115px);
    justify-content: flex-end;

    &-first {
        display: flex;
        align-items: center;

        &-date {
            margin-right: 5px;
        }
    }

    &-middle {
        margin: 0 10px;
    }

    &-second {
        display: flex;
        align-items: center;

        &-date {
            margin-right: 5px;
        }
    }
}
</style>